package com.tdk.wifidirectserver.adapter

import android.net.wifi.p2p.WifiP2pDevice
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.tdk.wifidirectserver.databinding.ItemLayoutBinding


//生成一个RecyclerView的适配器 用于显示蓝牙设备列表
class DeviceAdapter(diffCallback: ItemCallback<WifiP2pDevice>) :
    ListAdapter<WifiP2pDevice, BlueToothViewHolder>(diffCallback) {

    var onItemClickListener: ((WifiP2pDevice) -> Unit)? = null

    var onItemLongClickListener: ((WifiP2pDevice) -> Unit)? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BlueToothViewHolder {
        val binding = ItemLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return BlueToothViewHolder(binding)
    }

    override fun onBindViewHolder(holder: BlueToothViewHolder, position: Int) {
        val device = getItem(position)
        holder.bind(device)
        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(device)
        }
        holder.itemView.setOnLongClickListener {
            onItemLongClickListener?.invoke(device)
            true
        }
    }
}

//生成一个ViewHolder 用于显示蓝牙设备列表
class BlueToothViewHolder(private val binding: ItemLayoutBinding) : RecyclerView.ViewHolder(binding.root) {
    fun bind(device: WifiP2pDevice) {
        binding.tvDeviceName.text = device.toString()
//        binding.tvDeviceAddress.text = device.deviceAddress
//        binding.tvPrimaryDeviceType.text = device.primaryDeviceType
//        binding.tvSecondDeviceType.text = device.secondaryDeviceType
    }

}

class WifiP2pDeviceDiff : ItemCallback<WifiP2pDevice>() {
    override fun areItemsTheSame(oldItem: WifiP2pDevice, newItem: WifiP2pDevice): Boolean {
        return oldItem.deviceAddress == newItem.deviceAddress && oldItem.deviceName == newItem.deviceName && oldItem.primaryDeviceType == newItem.primaryDeviceType && oldItem.secondaryDeviceType == newItem.secondaryDeviceType && oldItem.status == newItem.status
    }


    override fun areContentsTheSame(oldItem: WifiP2pDevice, newItem: WifiP2pDevice): Boolean {
        return oldItem.deviceAddress == newItem.deviceAddress && oldItem.deviceName == newItem.deviceName && oldItem.primaryDeviceType == newItem.primaryDeviceType && oldItem.secondaryDeviceType == newItem.secondaryDeviceType && oldItem.status == newItem.status

    }
}


